<template>
    <div class="pageWrapper">
        <SearchBar class="form" @onSearch="handleSearch" @childFn="resetForm">
            <SearchBarItem label="商户号：" :labelLg="8">
                <Input
                    type="text"
                    v-model="dataModule.subMchId"
                    placeholder="请输入"
                    clearable
                />
            </SearchBarItem>
            <SearchBarItem label="商品名称：" :labelLg="8">
                <Input
                    type="text"
                    v-model="dataModule.productName"
                    placeholder="请输入"
                    clearable
                />
            </SearchBarItem>
            <SearchBarItem label="主订单：" :labelLg="8">
                <Input
                    type="text"
                    v-model="dataModule.orderId"
                    placeholder="请输入"
                    clearable
                />
            </SearchBarItem>
            <SearchBarItem label="子订单：" :labelLg="8">
                <Input
                    type="text"
                    v-model="dataModule.subOrderId"
                    placeholder="请输入"
                    clearable
                />
            </SearchBarItem>
            <!-- <SearchBarItem label="是否有记账数错误：" :labelLg="8">
                <Select
                    v-model="dataModule.isException"
                    placeholder="请选择"
                    :clearable="isClear"
                >
                    <Option
                        :value="item.key"
                        v-for="(item, key) in stateList"
                        :key="key"
                        >{{ item.value }}</Option
                    >
                </Select>
            </SearchBarItem> -->
            <SearchBarItem label="差异类型：" :labelLg="8">
                <Select
                    v-model="dataModule.error_type"
                    placeholder="请选择"
                    :clearable="isClear"
                >
                    <Option
                        :value="item.key"
                        v-for="(item, key) in errorTypeList"
                        :key="key"
                        >{{ item.value }}</Option
                    >
                </Select>
            </SearchBarItem>
            <SearchBarItem label="清分日期：" :labelLg="8">
                <DatePicker
                    type="daterange"
                    ref="clearDatePicker"
                    split-panels
                    transfer
                    :clearable="false"
                    placeholder="起始时间"
                    @on-change="clearTime"
                    :value="urlClearDate"
                ></DatePicker>
            </SearchBarItem>
            <SearchBarItem label="对账日期：" :labelLg="8">
                <DatePicker
                    type="daterange"
                    ref="billDatePicker"
                    split-panels
                    transfer
                    :clearable="false"
                    placeholder="起始时间"
                    @on-change="billTime"
                    :value="urlBillDate"
                ></DatePicker>
            </SearchBarItem>
            <SearchBarItem label="商品类型：" :labelLg="8">
                <Select
                    v-model="dataModule.orderSource"
                    placeholder="请选择"
                    :clearable="isClear"
                >
                    <Option
                        :value="item.key"
                        v-for="(item, key) in selectSource"
                        :key="key"
                        >{{ item.value }}</Option
                    >
                </Select>
            </SearchBarItem>
        </SearchBar>
        <RemoteTable
            ref="remoteTable"
            :namespace="namespace"
            :columns="columns"
            @onSortChange="onSortChange"
            :showPageInfo="false"
            :showCount="true"
            :isFixedHeader="true"
            :selected="exportData"
            @onSelectionChange="getListChecked"
        >
          <template #extra>
            <Authc permissions="trade:settlement:cmb">
              <Button type="primary" @click="exportExcel">导出</Button>
            </Authc>
            <Authc permissions="trade:settlement:cmb">
              <Button @click="toAbnormalHandle('abnormal')">批量处理</Button>
            </Authc>
            <Authc permissions="trade:settlement:cmb">
              <Button @click="toAbnormalHandle('remark')">批量备注</Button>
            </Authc>
          </template>

        </RemoteTable>
        <br />
        <Row>
            <Col span="12" offset="11">
                <Button
                    type="primary"
                    @click="loadMore"
                    :disabled="isDisabledloadBtn"
                    >加载更多</Button
                >
            </Col>
        </Row>
    </div>
</template>
<script>
import {
    Button,
    Input,
    Modal,
    Message,
    Col,
    Row,
    Form,
    FormItem,
    DatePicker,
    Select,
    Option
} from "view-design";
import RemoteTable from "@/components/RemoteTable";
import SearchBar from "@/components/SearchBar";
import { namespace } from "../Module/clearingAbnormalModule";
import Authc from "@/components/Authc";
import Action from "./Action";
import config from "@/utils/config";
import appService from "@/utils/appService";
import util from "@/utils/util";

export default {
    name: "clearingAbnormal",
    components: {
        RemoteTable,
        SearchBar,
        SearchBarItem: SearchBar.SearchBarItem,
        Authc,
        Action,
        Button,
        Input,
        Modal,
        Message,
        Col,
        Row,
        Form,
        FormItem,
        DatePicker,
        Select,
        Option,
    },
    data() {
        return {
            selectSource: [],
            requireUrl: "",
            namespace: namespace,
            isClear: true,
            loading: true,
            modal1: false,
            modal2: false,
            dataModule: {
                clearDateBegin: util.fun_date(-7),
                clearDateEnd: new Date().getFullYear() + '-' + (new Date().getMonth() + 1) + '-' + new Date().getDate()
            } /** 查询条件 **/,
            /** 是否有记账错误 **/
            stateList: [
                {
                    key: "1",
                    value: "是"
                },
                {
                    key: "0",
                    value: "否"
                }
            ],
            errorTypeList: [
                {
                    key: '0',
                    value: '平台有'
                },
                {
                    key: '1',
                    value: '平台无'
                }
            ],
            exportData: [] /** 存放导出的数据 **/,
            currentPage: 1 /** 用来控制加载更新 **/,
            isDisabledloadBtn: false /** 控制加载更多按钮 **/,
            batchData: [], /** 批量备注数据 **/
            urlClearDate: [util.fun_date(-7), new Date().getFullYear() + '-' + (new Date().getMonth() + 1) + '-' + new Date().getDate()],
            urlBillDate: [],
            columns: [
                {
                    title: "平台订单流水",
                    align: "center",
                    children: [
                        {
                            type: "selection",
                            align: "center",
                            minWidth: 55
                        },
                        {
                            title: "序号",
                            type: "index",
                            align: "center",
                            minWidth: 80
                        },
                        {
                            title: "清分日期",
                            key: "clearDate",
                            align: "center",
                            minWidth: 100
                        },
                        {
                            title: "主订单",
                            key: "orderId",
                            align: "center",
                            minWidth: 200
                        },
                        {
                            title: "子订单",
                            key: "subOrderId",
                            align: "center",
                            minWidth: 180
                        },
                        {
                            title: "商户号",
                            key: "subMchId",
                            align: "center",
                            minWidth: 200
                        },
                        {
                            title: "商品名称",
                            key: "productName",
                            align: "center",
                            minWidth: 200
                        },
                        {
                            title: "商品编码",
                            key: "productCode",
                            align: "center",
                            minWidth: 200
                        },
                        {
                            title: "清分金额(元)",
                            key: "clearAmount",
                            align: "center",
                            minWidth: 120,
                            render: (h, params) => {
                                let item = params.row.clearAmount ? params.row.clearAmount / 100 : 0;
                                return h('span', util.toMoney(item))
                            },
                        },
                        {
                            title: "清分记账数",
                            key: "clearCount",
                            align: "center",
                            minWidth: 100
                        }
                    ]
                },
                {
                    title: "银行订单流水",
                    key: "gender",
                    align: "center",
                    width: 200,
                    children: [
                        {
                            title: "招行订单号",
                            key: "bankOrderId",
                            align: "center",
                            minWidth: 210
                        },
                        {
                            title: "清分批次号",
                            key: "clearBatchNo",
                            align: "center",
                            minWidth: 180
                        },
                        {
                            title: "清分金额(元)",
                            key: "bankClearAmount",
                            align: "center",
                            minWidth: 120,
                            render: (h, params) => {
                                let item = params.row.bankClearAmount ? params.row.bankClearAmount / 100 : 0;
                                return h('span', util.toMoney(item))
                            },
                        },
                        {
                            title: "清分记账数",
                            key: "bankClearCount",
                            align: "center",
                            minWidth: 100
                        },
                        {
                            title: "对账日期",
                            key: "shouldBillDate",
                            align: "center",
                            minWidth: 170
                        },
                        {
                            title: "差异",
                            key: "errorAmount",
                            align: "center",
                            minWidth: 100,
                            render: (h, params) => {
                                let item = params.row.errorAmount / 100;
                                return h('span', util.toMoney(item));
                            }
                        }
                    ]
                },
                {
                    title: "对账结果",
                    key: "gender",
                    align: "center",
                    // fixed: "right",
                    children: [
                        {
                            title: "对账次数",
                            key: "billCount",
                            align: "center",
                            // fixed: "right",
                            minWidth: 100
                        },
                        {
                            title: "操作",
                            key: "action",
                            align: "center",
                            // fixed: "right",
                            permissions: ["invoice:taxpayer:detail"],
                            minWidth: 200,
                            render: function(h, data) {
                                return h(Action, {
                                    props: {
                                        row: data.row,
                                        showbtn: data.row.status != 3 ? true : false
                                    }
                                });
                            }
                        }
                    ]
                }
            ]
        };
    },
    created() {
         /**
         * 如果 url 没有带参数，就重置请求参数
         * 有就添加到 vuex
        * **/
       this.getKey();
        let subMchId = util.getUrlParam('subMchId');
        let clearDate = util.getUrlParam('clearDate');
        let subOrderId = util.getUrlParam('subOrderId');
        if( subMchId || clearDate || subOrderId ) {
            this.$store.commit(`${namespace}/setQuery`, {
                subMchId: subMchId,
                clearDateBegin: clearDate,
                clearDateEnd: clearDate,
                subOrderId: subOrderId
            });
            this.$set(this.dataModule, 'subMchId', subMchId);
            this.$set(this.dataModule, 'subOrderId', subOrderId);
            this.$set(this.urlClearDate, 0, clearDate);
            this.$set(this.urlClearDate, 1, clearDate);
        } else {
            // this.$store.commit(`${namespace}/reviseQuery`);
        }
    },
    activated() {
        this.dataModule = {}
        if (!JSON.parse(localStorage.getItem('data')) && !localStorage.getItem('newInter')) {
            this.dataModule = { subMchId: util.getUrlParam('subMchId'), subOrderId: util.getUrlParam('subOrderId') }
        console.log('-----创建-------1----')

        } else if (JSON.parse(localStorage.getItem('data')) && !localStorage.getItem('newInter')) {
            console.log('-----创建-------2----')

            let data = JSON.parse(localStorage.getItem('data')) ;
            this.urlClearDate = [];
            this.dataModule = { ...data, subMchId: util.getUrlParam('subMchId') || data.subMchId, subOrderId: util.getUrlParam('subOrderId') || data.subOrderId };
            if (this.dataModule.clearDateBegin) {
                this.$set(this.urlClearDate, 0, util.getUrlParam('clearDate') || this.dataModule.clearDateBegin);
                this.$set(this.urlClearDate, 1, util.getUrlParam('clearDate') || this.dataModule.clearDateEnd);
            }
            if (this.dataModule.shouldBillDateBegin) {
                this.$set(this.urlBillDate, 0, this.dataModule.shouldBillDateBegin);
                this.$set(this.urlBillDate, 1, this.dataModule.shouldBillDateEnd);
            }

        } else if (localStorage.getItem('newInter')) {
            console.log('-----创建-------3----')
            this.dataModule = { subMchId: util.getUrlParam('subMchId'), subOrderId: util.getUrlParam('subOrderId') }
            console.log(JSON.parse(localStorage.getItem('data')), '==========-------------刷新页面-------------=======')
        }
    },
    deactivated () {
        if (window.location.pathname.indexOf('ClearingAbnormalForm') > -1 || window.location.pathname.indexOf('ClearingAbnormalMatch') > -1 || window.location.pathname.indexOf('ClearingAbnormaRemarklForm') > -1 || window.location.pathname.indexOf('ClearingAbnormalRemark') > -1) {
            console.log('----销毁----1----')
        } else {
            console.log('------销毁-----2------')
            this.$store.commit(`${namespace}/reviseQuery`);
            localStorage.removeItem('data');
            this.dataModule = {}
        };
        window.removeEventListener('beforeunload', e => this.beforeunloadHandler(e));
        localStorage.removeItem('newInter');

    },
    mounted() {
        setTimeout(() => {
            this.loading = false;
        }, 1000);
        window.addEventListener('beforeunload', e => {
            localStorage.setItem('newInter', true);
            this.newInter = true;
            this.beforeunloadHandler(e)
        });
    },
    methods: {
        /** 字典 - 商品类型 */
        async getKey() {
            try {
                let res = await this.$store.dispatch(`${namespace}/getMerchantSearchKey`);
                if (res.data.ret === 0) {
                    let data = res.data.data;
                    this.selectSource = data.orderSource; // 商品类型
                }
            } catch (error) {
                this.$Message.error({
                    content: error
                })
            }
        },
        beforeunloadHandler (e) {
            e = e || window.event;
            // if (e) {
            //     e.returnValue = '关闭提示'
            // }
            return '关闭提示'
        },
        /** 导出 **/
        exportExcel() {
            if (this.exportData.length == 0) {
                this.$Message.error({
                    content: "请选择导出的数据"
                });
                return;
            } else {
                this.exportData.forEach(e => {
                    // if (e.clearAmount || e.bankClearAmount) {
                    //     e.clearAmount = e.clearAmount / 100
                    //     e.bankClearAmount = e.bankClearAmount / 100
                    // }
                    e.clearDate = e.clearDate || ''
                    e.orderId = e.orderId || ''
                    e.subOrderId = e.subOrderId || ''
                    e.subMchId = e.subMchId || ''
                    e.productName = e.productName || ''
                    e.clearAmount = (e.clearAmount / 100) || '\t0'
                    e.clearCount = e.clearCount || '\t0'
                    e.bankOrderId = e.bankOrderId || ''
                    e.clearBatchNo = e.clearBatchNo || ''
                    e.bankClearAmount = (e.bankClearAmount / 100) || '\t0'
                    e.bankClearCount = e.bankClearCount || '\t0'
                    e.statementDate = e.statementDate || ''
                    e.errorAmount = (e.errorAmount / 100) || '\t0'
                    e.billCount = e.billCount || '\t0'

                })
            }

            /** 多表头处理 **/
            let exportColumn = this.handleMultiTableHeader(this.columns, false);

            /** 复制一份表头 **/
            let columnOne = {};
            exportColumn.forEach(item => {
                columnOne[item.key] = item.title;
            });

            /** 自定义导出表格第一行的表头，逗号表示隔开几个单元格 **/
            let tableTitle = {
                clearDate: `${this.columns[0].title},,,,,,,${this.columns[1].title},,,,,,${this.columns[2].title}`,
                orderId: "",
                subOrderId: "",
                subMchId: "",
                productName: "",
                clearAmount: "",
                clearCount: "",
                bankOrderId: "",
                clearBatchNo: "",
                bankClearAmount: "",
                bankClearCount: "",
                statementDate: "",
                errorAmount: "",
                billCount: ""
            };
            /** 复制一份导出数据 **/
            let copyTableData = JSON.parse(JSON.stringify(this.exportData));

            /** 把自定义的表头和复制出来的表头，添加到导出数据前面 **/
            copyTableData.unshift(tableTitle, columnOne);
            console.log(copyTableData)

            let tables = this.$refs.remoteTable.getTables();
            tables.exportCsv({
                filename: "清分异常",
                columns: exportColumn,
                data: copyTableData.map(item => {
                    return {
                        clearDate: `\t${item.clearDate}`,
                        orderId: `\t${item.orderId}`,
                        subOrderId: `\t${item.subOrderId}`,
                        subMchId: `\t${item.subMchId}`,
                        productName:  `\t${ item.productName }`,
                        clearAmount: `\t${item.clearAmount}`,
                        clearCount: `\t${item.clearCount}`,
                        bankOrderId: `\t${item.bankOrderId}`,
                        clearBatchNo: `\t${item.clearBatchNo}`,
                        bankClearAmount: `\t${item.bankClearAmount}`,
                        bankClearCount: `\t${item.bankClearCount}`,
                        statementDate: `\t${item.statementDate}`,
                        errorAmount: `\t${item.errorAmount}`,
                        billCount: `\t${item.billCount}`,
                    };
                }),
                noHeader: true
            });
        },
        handleSearch() {
            this.currentPage = 1;
            let obj = {
                currentPage: 1,
                pageSize: 10
            };
            this.$store.dispatch(`${namespace}/query`, this.dataModule);
            localStorage.removeItem('data');
            localStorage.setItem('data', JSON.stringify(this.dataModule));
        },
        onSortChange(sort) {
            if (sort.order === "normal") {
                this.queryParam.order = [];
            } else {
                this.queryParam.order = [sort.key + " " + sort.order];
            }
            this.handleSearch();
        },
        /** 清空事件； **/
        resetForm() {
            this.$store.commit(`${namespace}/reviseQuery`);
            this.$set(this.dataModule, "subMchId", "");
            this.$set(this.dataModule, "productName", "");
            this.$set(this.dataModule, "orderId", "");
            this.$set(this.dataModule, "subOrderId", "");
            this.$set(this.dataModule, "isException", "");
            this.$set(this.dataModule, "error_type", "");
            this.$set(this.dataModule, 'clearDateBegin', '')
            this.$set(this.dataModule, 'clearDateEnd', '');
            this.$set(this.dataModule, "orderSource", "");
            // 清空时间选择
            this.$refs["clearDatePicker"].handleClear();
            this.$refs["billDatePicker"].handleClear();
        },
        /** 清分日期 **/
        clearTime(date, type) {
            this.dataModule.clearDateBegin = date ? date[0] : "";
            this.dataModule.clearDateEnd = date ? date[1] : "";
            this.urlClearDate = date;
        },
        /** 对账时间 **/
        billTime(date, type) {
            this.dataModule.shouldBillDateBegin = date ? date[0] : "";
            this.dataModule.shouldBillDateEnd = date ? date[1] : "";
        },
        /** 加载更多 **/
        async loadMore() {
            try {
                let objs
                if (util.getUrlParam('subMchId') || util.getUrlParam('clearDate') || util.getUrlParam('subOrderId')) {
                    objs = {
                        subMchId: util.getUrlParam('subMchId'),
                        clearDateBegin: util.getUrlParam('clearDate'),
                        clearDateEnd: util.getUrlParam('clearDate'),
                        subOrderId: util.getUrlParam('subOrderId')
                    }
                }

                this.isDisabledloadBtn = true; // 每次请求都禁止按钮点击
                let obj = {
                        currentPage: ++this.currentPage,
                        pageSize: 50
                    };

                let params
                if (this.urlClearDate) {
                    params = { ...this.dataModule, ...objs, ...obj, clearDateBegin: this.urlClearDate[0], clearDateEnd: this.urlClearDate[1] }
                } else {
                    params = { ...objs, ...this.dataModule, ...obj }
                }
                /** 因为不是翻页，所以重新写了一个列表的请求 **/
                let res = await this.$store.dispatch(
                    `${namespace}/getMoreList`,
                    params
                );
                let listData = res.data.data.list;
                if (listData.length != 0) {
                    /** 拿到数据，就拼接到 vuex 里面 **/
                    this.$store.commit(`${namespace}/pushDataToList`, listData);
                } else {
                    --this.currentPage;
                    this.$Message.info({
                        content: '没有更多数据了！'
                    });
                }
                this.isDisabledloadBtn = false;
            } catch (error) {
                this.$Message.error({
                    content: error
                });
            }
        },
        /** 列表选择 **/
        getListChecked(data) {
            this.exportData = data;
            this.batchData = data;
        },
        /** cy 处理多表头导出问题 **/
        handleMultiTableHeader(columns) {
            return columns.map(res => {
                if (res.hasOwnProperty("children")) {
                    /** 通过 key 过滤掉 复选框和序号还有操作栏 **/
                    return res.children.filter(item => {
                        return item.key;
                    });
                } else {
                    return res;
                }
            }).flat();
        },
        toAbnormalHandle(type){
            switch (type) {
                case 'abnormal':
                    this.$router.push({
                        path: '/settlement/admin/SettlementCenter/ClearingAbnormalMatch',
                    });
                    break
                case 'remark':
                    if (this.batchData.length == 0) {
                        this.$Message.warning({
                            content: "请选择需要处理的内容"
                        });
                        return;
                    }
                    /** 把批量数据存起来放到 本地，可以刷新 **/
                    sessionStorage.setItem(`${namespace}/batchData`,JSON.stringify(this.batchData));
                    this.$router.push({
                        path: '/settlement/admin/SettlementCenter/ClearingAbnormalRemark',
                    });
                    break
                default:
            }
        }
    }
};
</script>
<style scoped></style>
